import {
  SAVE_COMMENT_RESULT,
  SET_COMMENT_QUERY_PAGE_PAGE,
  SET_PARENT_COMMENT_ID,
  RESET_COMMENT_FORM,
  RESTORE_COMMENT_FORM,
  SET_COMMENT_QUERY_COMMENT_TYPE,
  SET_COMMENT_QUERY_RELEVANT_ID,
} from "@/store/mutations-types"
import Vue from 'vue'
import { getCommentListByQuery, submitComment } from "@/api/comment"
import { Notification } from "element-ui"
import tvMapper from '@/plugins/tvMapper.json'
import aruMapper from '@/plugins/aruMapper.json'
import paopaoMapper from '@/plugins/paopaoMapper.json'
import sanitizeHtml from 'sanitize-html'

const comment = {
  state: {
    commentQuery: {
      //用于后端判断该评论所在页面类型(文章、友链、关于我)
      commentType: 1,
      /**
       * 目前特指博客id
       */
      relevantId: null,
      page: {
        page: 1,
        limit: 5
      },
      /**
       * 博客文章密码生成的token
       */
      token: ''
    },
    /**
     * 评论总数
     */
    allComment: 0,
    /**
     * 隐藏评论数量
     */
    closeComment: 0,
    /**
     * 评论总页数
     */
    commentTotalPage: 0,
    /**
     * 评论集合
     */
    comments: [],
    /**
     * 父评论标识
     */
    parentCommentId: -1,
    /**
     * 评论者数据，会做缓存放到本地
     */
    commentForm: {
      content: '',
      nickname: '',
      email: '',
      website: '',
      notice: true
    },
  },

  mutations: {
    [SAVE_COMMENT_RESULT] (state, data) {
      state.allComment = data.allComment
      state.closeComment = data.closeComment
      state.commentTotalPage = data.comments.totalPage
      state.comments = data.comments.rows
    },
    [SET_COMMENT_QUERY_COMMENT_TYPE] (state, commentType) {
      state.commentQuery.commentType = commentType
    },
    [SET_COMMENT_QUERY_RELEVANT_ID] (state, relevantId) {
      state.commentQuery.relevantId = relevantId
    },
    [SET_COMMENT_QUERY_PAGE_PAGE] (state, pageNum) {
      state.commentQuery.page.page = pageNum
    },
    [SET_PARENT_COMMENT_ID] (state, parentCommentId) {
      state.parentCommentId = parentCommentId
    },
    [RESET_COMMENT_FORM] (state) {
      const commentForm = {
        nickname: state.commentForm.nickname,
        email: state.commentForm.email,
        website: state.commentForm.website
      }
      //保存访客信息，下次评论时自动填充表单
      Vue.ls.set('commentForm', JSON.stringify(commentForm))
      state.commentForm.content = ''
      state.commentForm.notice = true
    },
    [RESTORE_COMMENT_FORM] (state) {
      const lastForm = JSON.parse(Vue.ls.get('commentForm'))
      if (lastForm) {
        state.commentForm.nickname = lastForm.nickname
        state.commentForm.email = lastForm.email
        state.commentForm.website = lastForm.website
      }
    },
  },

  actions: {
    getCommentList ({ commit, rootState }) {
      //密码保护的文章，需要发送密码验证通过后保存在localStorage的Token
      const blogToken = Vue.ls.get(`blog${rootState.comment.commentQuery.relevantId}`)

      function replaceEmoji (comment, emoji) {
        comment.content = comment.content.replace(new RegExp(emoji.reg, 'g'), `<img src="${emoji.src}">`)
      }
      function convertEmoji (comment) {
        tvMapper.forEach(emoji => {
          replaceEmoji(comment, emoji)
        })
        aruMapper.forEach(emoji => {
          replaceEmoji(comment, emoji)
        })
        paopaoMapper.forEach(emoji => {
          replaceEmoji(comment, emoji)
        })
      }
      rootState.comment.commentQuery.token = blogToken
      getCommentListByQuery(rootState.comment.commentQuery).then(res => {
        let sanitizeHtmlConfig = {
          allowedTags: [],
          allowedAttributes: false,
          disallowedTagsMode: 'recursiveEscape'
        }
        res.data.comments.rows.forEach(comment => {
          //转义评论中的html
          comment.content = sanitizeHtml(comment.content, sanitizeHtmlConfig)
          //查找评论中是否有表情
          if (comment.content.indexOf('@[') != -1) {
            convertEmoji(comment)
          }
          comment.children.forEach(comment => {
            //转义评论中的html
            comment.content = sanitizeHtml(comment.content, sanitizeHtmlConfig)
            //查找评论中是否有表情
            if (comment.content.indexOf('@[') != -1) {
              convertEmoji(comment)
            }
          })
        })
        commit(SAVE_COMMENT_RESULT, res.data)
      })
    },
    submitCommentForm ({ rootState, dispatch, commit }, token) {
      const adminToken = Vue.ls.get('access_token')
      let form = { ...rootState.comment.commentForm }
      form.commentType = rootState.comment.commentQuery.commentType
      form.relevantId = rootState.comment.commentQuery.relevantId
      form.parentCommentId = rootState.comment.parentCommentId
      form.token = token
      form.adminComment = adminToken ? true : false
      submitComment(form).then(res => {
        if (res.code === 0) {
          Notification({
            title: res.msg,
            type: 'success'
          })
          commit(SET_PARENT_COMMENT_ID, -1)
          commit(RESET_COMMENT_FORM)
          dispatch('getCommentList')
        } else {
          Notification({
            title: '评论失败',
            message: res.msg,
            type: 'error'
          })
        }
      }).catch(() => {
        Notification({
          title: '评论失败',
          message: '异常错误',
          type: 'error'
        })
      })
    },
  }
}

export default comment